var Question = mongoose.model('question');
var Dic = mongoose.model('masterData_Dictionaries');
var Community = mongoose.model('community');
var Users = mongoose.model('user');
var async = require('async');
var moment = require('moment');
var ugcIndex = mongoose.model('system_ugcIndex');


exports.backPostQuestionService = function (input, callback) {

    input.desc = input.desc.replace(/[\n\r]{2,}/g, "\n").trim();

    async.each(input.community, function (community, callbackInner) {
        Users.findOne({community: community, userType: 'service'}, function (err, service) {
            if (service == null) {
                Users.findOne({mobilePhone: '66customerservice'}, function (err, service) {
                    exports.saveQuestion(input, community, service, callbackInner);
                })
            } else {
                exports.saveQuestion(input, community, service, callbackInner);
            }
        })
    }, callback);
};


exports.saveQuestion = function (input, community, service, callback) {
    var questionId;
    async.series([
        function (c1) {
            var temp = new Question();
            temp.category = input.category;
            temp.desc = input.desc;
            temp.images = input.images;
            temp.createdBy = service._id;
            temp.community = community;
            temp.tag = input.tag;
            questionId = temp._id;
            temp.save(c1)
        },
        function (c2) {
            redisClient.hincrby('q:count:' + community, input.category + 'QuestionCount', 1);
            var temp = new ugcIndex();
            temp.ugcId = questionId;
            temp.category = input.category;
            temp.community = community;
            temp.createdBy = service._id;
            temp.tag = input.tag;
            temp.save(c2);
        }
    ], callback);
};